<?php
/**
 * Created by PhpStorm.
 * @author caoning
 * @date 2021/7/20 19:57
 */

namespace App\Http\Controllers;

use  Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SsqController extends BaseController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        return view('ssq/index');
    }

    public function list()
    {
        return view('ssq/list');
    }

    public function detail()
    {
        return view('ssq/detail');
    }

    public function share()
    {
        return view('ssq/share');
    }

    public function save(Request $request)
    {
        $params = $request->all();

        // 数据校验
        $data = [];
        if (!empty($params['name'])) {
            $data['name'] = $params['name'];
        }
        if (!empty($params['title'])) {
            $data['title'] = $params['title'];
        }
        if (!empty($params['subtitle'])) {
            $data['subtitle'] = $params['subtitle'];
        }

        if (isset($params['id'])) {
            $id = $params['id'];
            $ret = Db::table('cate')->where('id', $params['id'])->update($data);
        } else {
            $id = $ret = Db::table('cate')->insertGetId($data);
        }

        response_json($ret ? 0 : 1, $ret ? '保存成功！' : '保存失败，请联系管理员！', ['id' => $id]);
    }

    public function getOne(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        // 查询栏目详情
        $data = Db::table('cate')->where('id', $params['id'])->first();
        if (!empty($data->id)) {
            // 获取数据
            $data->leftData = Db::table('data')->where('cate_id', $params['id'])
                ->where('type', 'left')
                ->where('is_deleted', 0)
                ->get()
                ->toArray();
            $data->rightData = Db::table('data')->where('cate_id', $params['id'])
                ->where('type', 'right')
                ->where('is_deleted', 0)
                ->get()
                ->toArray();
        }

        response_json($data ? 0 : 1, $data ? '' : '系统异常，请联系管理员！', $data);
    }

    public function getList(Request $request)
    {
        $params = $request->all();
        $params['page_size'] = empty($params['page_size']) ? 15 : $params['page_size'];
        $params['current_page'] = empty($params['current_page']) ? 1 : $params['current_page'];
        $params['keywords'] = empty($params['keywords']) ? '' : trim($params['keywords']);

        $where = [['is_deleted', '=', '0']];
        if (!empty($params['keywords'])) {
            $where[] = ['name', 'like', "%{$params['keywords']}%"];
        }
        $data = DB::table('cate')
            ->select('*')
            ->where($where)
            ->orderBy('created_on', 'desc')
            ->paginate($params['page_size'], ['*'], 'page', $params['current_page']);

        response_json(0, '', $data);
    }

    public function del(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数有误，请联系管理员！');
        }
        $ret = Db::table('cate')->where('id', $params['id'])->update(['is_deleted' => 1]);
        response_json($ret ? 0 : 1, $ret ? '删除成功！' : '删除失败，请联系管理员！');
    }

    public function saveData(Request $request)
    {
        $params = $request->all();

        // 数据校验
        $data = [];
        if (!empty($params['cate_id'])) {
            $data['cate_id'] = $params['cate_id'];
        }
        if (!empty($params['one'])) {
            $data['one'] = $params['one'];
        }
        if (!empty($params['two'])) {
            $data['two'] = $params['two'];
        }
        if (!empty($params['three'])) {
            $data['three'] = $params['three'];
        }
        if (!empty($params['four'])) {
            $data['four'] = $params['four'];
        }
        if (!empty($params['five'])) {
            $data['five'] = $params['five'];
        }
        if (!empty($params['six'])) {
            $data['six'] = $params['six'];
        }
        if (!empty($params['seven'])) {
            $data['seven'] = $params['seven'];
        }
        if (!empty($params['type'])) {
            $data['type'] = $params['type'];
        }

        if (isset($params['id'])) {
            $id = $params['id'];
            $ret = Db::table('data')->where('id', $params['id'])->update($data);
        } else {
            $id = $ret = Db::table('data')->insertGetId($data);
        }

        response_json($ret ? 0 : 1, $ret ? '保存成功！' : '保存失败，请联系管理员！', ['id' => $id]);
    }

    public function delData(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数有误，请联系管理员！');
        }
        $ret = Db::table('data')->where('id', $params['id'])->update(['is_deleted' => 1]);
        response_json($ret ? 0 : 1, $ret ? '删除成功！' : '删除失败，请联系管理员！');
    }

    public function generateShare(Request $request)
    {
        $params = $request->all();
        if (empty($params['cate_id'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        $data = [
            'cate_id' => $params['cate_id'],
            'uuid' => $this->uuid(),
        ];

        $id = $ret = Db::table('share')->insertGetId($data);

        response_json($ret ? 0 : 1, $ret ? '保存成功！' : '保存失败，请联系管理员！', ['id' => $id, 'uuid' => $data['uuid']]);
    }

    public function getShareInfo(Request $request)
    {
        $params = $request->all();
        if (empty($params['uuid'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        // 查询分享信息
        $data = [];
        $share = Db::table('share')->where('uuid', $params['uuid'])->where('is_deleted', 0)->first();
        if ($share) {
            // 查询栏目详情
            $data = Db::table('cate')->where('id', $share->cate_id)->where('is_deleted', 0)->first();
            if (!empty($data->id)) {
                // 获取数据
                $data->leftData = Db::table('data')->where('cate_id', $share->cate_id)
                    ->where('type', 'left')
                    ->where('is_deleted', 0)
                    ->get()
                    ->toArray();
                $data->rightData = Db::table('data')->where('cate_id', $share->cate_id)
                    ->where('type', 'right')
                    ->where('is_deleted', 0)
                    ->get()
                    ->toArray();
            }
        }

        response_json($data ? 0 : 1, $data ? '' : '系统异常，请联系管理员！', $data);
    }

    public function copyCate(Request $request)
    {
        $params = $request->all();
        if (empty($params['id']) || empty($params['name'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        $cate = Db::table('cate')->where('id', $params['id'])->first();
        $data = Db::table('data')->where('cate_id', $params['id'])
            ->where('is_deleted', 0)
            ->get()
            ->map(function ($value){
                return (array)$value;
            })
            ->toArray();
        $row = ['name' => $params['name'], 'title' => $cate->title, 'subtitle' => $cate->subtitle];
        $id = Db::table('cate')->insertGetId($row);

        foreach ($data as $r) {
            $r['cate_id'] = $id;
            unset($r['created_on']);
            unset($r['modified_on']);
            unset($r['id']);
            Db::table('data')->insertGetId($r);
        }

        response_json($id ? 0 : 1, $id ? '复制成功' : '系统异常，请联系管理员！', ['id' => $id]);
    }

    public function deleteData(Request $request)
    {
        $params = $request->all();
        if (empty($params['id'])) {
            response_json(1, '参数丢失，请联系管理员！');
        }

        Db::table('cate')->where('id', $params['id'])->update(['title' => '', 'subtitle' => '']);
        $ret = Db::table('data')->where('cate_id', $params['id'])->update(['is_deleted' => 1]);

        response_json($ret ? 0 : 1, $ret ? '删除成功！' : '删除失败，请联系管理员！');
    }

    public function uuid()
    {
        list($usec, $sec) = explode(" ", microtime(false));
        $usec             = (string) ($usec * 10000000);
        $timestamp        = bcadd(bcadd(bcmul($sec, "10000000"), (string) $usec), "621355968000000000");
        $ticks            = bcdiv($timestamp, 10000);
        $maxUint          = 4294967295;
        $high             = bcdiv($ticks, $maxUint) + 0;
        $low              = bcmod($ticks, $maxUint) - $high;
        $highBit          = (pack("N*", $high));
        $lowBit           = (pack("N*", $low));
        $guid             = str_pad(dechex(ord($highBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($highBit[3])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[0])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[1])), 2, "0", STR_PAD_LEFT) . "-" . str_pad(dechex(ord($lowBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[3])), 2, "0", STR_PAD_LEFT) . "-";
        $chars            = "abcdef0123456789";
        for ($i = 0; $i < 4; $i++) {
            $guid .= $chars[mt_rand(0, 15)];
        }
        $guid .= "-";
        for ($i = 0; $i < 4; $i++) {
            $guid .= $chars[mt_rand(0, 15)];
        }
        $guid .= "-";
        for ($i = 0; $i < 12; $i++) {
            $guid .= $chars[mt_rand(0, 15)];
        }

        return $guid;
    }
}
